package translinkApp.Data.Parse.Locations;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPather;
import org.htmlcleaner.XPatherException;

import android.content.Context;

import translinkApp.Data.ResolvedLocation.ResolvedLocation;
import translinkApp.Data.ResolvedLocation.ResolvedLocationList;

public class LocationsParse {

	public static ResolvedLocationList getLocationsList(Context c, String street, String suburb,
			boolean isStreet) {

		ResolvedLocationList locations = new ResolvedLocationList();

		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node;

		try {
			String data = new GetLocationData().getData(c, street, suburb);
			node = cleaner.clean(data);

			XPather pather = new XPather("//label[@class = 'radio']");

			Object[] nameObjects = pather.evaluateAgainstNode(node);

			int added = 0;
			for (int i = 0; i < nameObjects.length; i++) {

				TagNode nodeval = ((TagNode) nameObjects[i]);
				if (nodeval.getAttributeByName("for").contains("from")) {

					locations.add(new ResolvedLocation(nodeval.getText().toString().trim(), nodeval
							.getText().toString().trim(), isStreet));
					added++;
					if (i > 6)
						break;
				}
			}

			if (added == 0) {

				Object nameObject = getNodeText(node, "//span[@class = 'exactMatch']/text()")[0];

				locations.add(new ResolvedLocation(nameObject.toString().trim(), nameObject
						.toString().trim(), isStreet));
			}

		} catch (Exception e) {

			e.printStackTrace();
			locations = new ResolvedLocationList();
		}

		return locations;

	}

	public static String encodeUrlString(String url) {
		try {
			return URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return url;
	}

	public static Object[] getNodeText(TagNode mainNode, String xpath) {
		XPather pather = new XPather(xpath);

		Object[] objects;
		try {
			objects = pather.evaluateAgainstNode(mainNode);

			return objects;

		} catch (XPatherException e) {

			e.printStackTrace();
		}

		return null;

	}

	public static String getNodeAttribute(TagNode mainNode, String xpath, String attribute) {
		XPather pather = new XPather(xpath);

		Object[] objects;
		try {
			objects = pather.evaluateAgainstNode(mainNode);

			for (Object obj : objects) {

				TagNode nodeval = ((TagNode) obj);
				return nodeval.getAttributeByName(attribute);
			}

		} catch (XPatherException e) {

			e.printStackTrace();
		}
		return "";
	}
}
